package com.xq.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @title: JtwToken
 * @Author Tan
 * @Date: 2020/8/5 23:09
 * @Version 1.0
 */
public class JwtToken {
    public static final String TOKEN_HEADER = "Token";
    public static final String TOKEN_PREFIX = "Bearer ";
    // 过期时间，这里设为30分钟
    private static final long EXPIRE_TIME = 30 * 60 * 1000;
    // 密钥
    public static final String SECRET = "Jamie";

    public String createJwt(String username,String id) {
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setSubject(username)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE_TIME));

        return builder.compact();
    }

    public String parseJwt(String toke) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(toke).getBody();
        return claims.getSubject();
    }
}